package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sql.TeamMemberDao;
import beans.TeamMemberItemBean;

/**
 * Servlet implementation class AddTeamMember
 */
@WebServlet("/AddTeamMember")
public class AddTeamMember extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddTeamMember() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int roleId = 0;
		Integer projectId = 0;
		
		try {
			roleId = Integer.parseInt(request.getParameter("role"));
			projectId= Integer.parseInt(request.getParameter("project"));
		}
		catch (NumberFormatException e) {
			// Should not be invalid as these values come from dropdowns
		}
		TeamMemberItemBean teamMemberItem = new TeamMemberItemBean();
		teamMemberItem.setName(request.getParameter("name"));
		teamMemberItem.setRoleId(roleId);
		teamMemberItem.setProjectId(projectId);
		teamMemberItem.setEmail(request.getParameter("email"));
		teamMemberItem.setPassword(request.getParameter("password"));
		
		TeamMemberDao teamMemberDao = new TeamMemberDao();
		try {
			teamMemberDao.insert(teamMemberItem);
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
		
		// return data
		PrintWriter out = response.getWriter();
		out.write(teamMemberItem.getJson());
	}

}
